package com.jihox.abookpro.dao;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.jihox.abookpro.domain.BookProject;
import com.jihox.abookpro.domain.Order;
import com.jihox.abookpro.util.DBHelper;

public class OrderDAO {

	private Context context;
	private DBHelper dbhelper;
	private SQLiteDatabase sqlitedatabase;

	public OrderDAO(Context context) {
		super();
		this.context = context;
	}

	// 打开数据库连接
	public void opendb() {
		dbhelper = new DBHelper(context);
		sqlitedatabase = dbhelper.getWritableDatabase();
	}

	// 关闭数据库连接
	public void closedb() {
		if (sqlitedatabase != null && sqlitedatabase.isOpen()) {
			sqlitedatabase.close();
		}
	}

	public void addOrderInfo(Order order) {

		ContentValues cv = new ContentValues();
		cv.put("OrderId", order.getOrderId());
		cv.put("Worksn", order.getWorksn());
		cv.put("BookProject", order.getBookProject().toString());
		cv.put("OrderStatus", order.getOrderStatus());
		cv.put("OrderDeliveryCycle", order.getOrderDeliveryCycle());
		cv.put("TemplateName", order.getTemplateName());
		final ByteArrayOutputStream os = new ByteArrayOutputStream();
		order.getThumbnail().compress(Bitmap.CompressFormat.PNG, 100, os);
		cv.put("Thumbnail", os.toByteArray());
		
		opendb();
		sqlitedatabase.insert("orders", null, cv);
		closedb();
	}

	public void updateOrderStatus(Order order) {

		ContentValues cv = new ContentValues();
		cv.put("OrderStatus", order.getOrderStatus());
		opendb();
		sqlitedatabase.update("orders", cv, "OrderId = ? ",
				new String[] { order.getOrderId() });
		closedb();
	}
	
	public void updateOrderFileUrl(Order order) {

		ContentValues cv = new ContentValues();
		cv.put("FileUrl", order.getUploadedFileUrl());
		opendb();
		sqlitedatabase.update("orders", cv, "OrderId = ? ",
				new String[] { order.getOrderId() });
		closedb();
	}
	
	public void updateOrderFileCrc(Order order) {

		ContentValues cv = new ContentValues();
		cv.put("ZipFileCrc", order.getZipFileCrc());
		cv.put("ZipFileSize", order.getZipFileSize());
		cv.put("OrderStatus", order.getOrderStatus());
		
		opendb();
		sqlitedatabase.update("orders", cv, "OrderId = ? ",
				new String[] { order.getOrderId() });

		closedb();
	}
	
	public void updateOrderFilePath(String orderId,String filePath) {

		ContentValues cv = new ContentValues();
		cv.put("ZipFilePath", filePath);
		
		opendb();
		sqlitedatabase.update("orders", cv, "OrderId = ? ",
				new String[] { orderId });

		closedb();
	}

	public void DeleteOrderInfo(String orderId) {

		opendb();
		try {
			sqlitedatabase.delete("orders", "OrderId = ? ",
					new String[] { orderId });
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			closedb();
		}
	}
	
	public HashMap<String,Order> getOrderInfoMap() {
		HashMap<String,Order> orderList = new HashMap<String,Order>();
		opendb();
		Cursor c = sqlitedatabase.rawQuery("SELECT * FROM orders", null);

		while (c.moveToNext()) {
			Order order = new Order();
			order.setOrderId( c.getString(c.getColumnIndex("OrderId")));
			order.setOrderStatus( c.getInt(c.getColumnIndex("OrderStatus")));
			order.setWorksn(c.getString(c.getColumnIndex("Worksn")));
			order.setZipFilePath(c.getString(c.getColumnIndex("ZipFilePath")));
			order.setZipFileCrc(c.getString(c.getColumnIndex("ZipFileCrc")));
			order.setZipFileSize(c.getLong(c.getColumnIndex("ZipFileSize")));
			order.setOrderDeliveryCycle(c.getString(c.getColumnIndex("OrderDeliveryCycle")));
			order.setTemplateName(c.getString(c.getColumnIndex("TemplateName")));
	
			BookProject project = BookProject.parse(c.getString(c.getColumnIndex("BookProject")));
			if (project == null){
				continue;
			}else{
				order.setBookProject(project);
			}
			byte[] in=c.getBlob(c.getColumnIndex("Thumbnail"));  
			order.setThumbnail(BitmapFactory.decodeByteArray(in,0,in.length));  

			orderList.put(order.getOrderId(),order);
		}
		c.close();
		closedb();
		return orderList;
	}
	
	public List<Order> getOrderInfoList() {
		ArrayList<Order> orderList = new ArrayList<Order>();
		opendb();
		Cursor c = sqlitedatabase.rawQuery("SELECT * FROM orders", null);

		while (c.moveToNext()) {
			Order order = new Order();
			order.setOrderId( c.getString(c.getColumnIndex("OrderId")));
			order.setOrderStatus( c.getInt(c.getColumnIndex("OrderStatus")));
			order.setWorksn(c.getString(c.getColumnIndex("Worksn")));
			order.setZipFilePath(c.getString(c.getColumnIndex("ZipFilePath")));
			order.setZipFileCrc(c.getString(c.getColumnIndex("ZipFileCrc")));
			order.setZipFileSize(c.getLong(c.getColumnIndex("ZipFileSize")));
			order.setTemplateName(c.getString(c.getColumnIndex("TemplateName")));
			order.setOrderDeliveryCycle(c.getString(c.getColumnIndex("OrderDeliveryCycle")));
			BookProject project = BookProject.parse(c.getString(c.getColumnIndex("BookProject")));
			if (project == null){
				continue;
			}else{
				order.setBookProject(project);
			}
			byte[] in=c.getBlob(c.getColumnIndex("Thumbnail"));  
			order.setThumbnail(BitmapFactory.decodeByteArray(in,0,in.length));  

			orderList.add(order);
		}
		c.close();
		closedb();
		return orderList;
	}
	
	public Order getOrderInfo(String orderId){
		
		if(this.sqlitedatabase == null || !this.sqlitedatabase.isOpen()){
			opendb();
		}
		Cursor c = sqlitedatabase.rawQuery("SELECT * FROM orders where OrderId = '" + orderId +"'", null);
		Order order = null;
		
		while (c.moveToNext()) {
			order = new Order();
			order.setOrderId( c.getString(c.getColumnIndex("OrderId")));
			order.setOrderStatus( c.getInt(c.getColumnIndex("OrderStatus")));
			order.setWorksn(c.getString(c.getColumnIndex("Worksn")));
			order.setZipFilePath(c.getString(c.getColumnIndex("ZipFilePath")));
			order.setZipFileCrc(c.getString(c.getColumnIndex("ZipFileCrc")));
			order.setZipFileSize(c.getLong(c.getColumnIndex("ZipFileSize")));
			order.setTemplateName(c.getString(c.getColumnIndex("TemplateName")));
			order.setOrderDeliveryCycle(c.getString(c.getColumnIndex("OrderDeliveryCycle")));
			BookProject project = BookProject.parse(c.getString(c.getColumnIndex("BookProject")));
			order.setBookProject(project);
			byte[] in=c.getBlob(c.getColumnIndex("Thumbnail"));  
			order.setThumbnail(BitmapFactory.decodeByteArray(in,0,in.length));  

		}
		c.close();
		return order;
	}
	
	public Bitmap getOrderThumbnail(String orderId){
		Bitmap thumbnail =null;
		if(this.sqlitedatabase == null || !this.sqlitedatabase.isOpen()){
			opendb();
		}
		Cursor c = sqlitedatabase.rawQuery("SELECT * FROM orders where OrderId = '" + orderId +"'", null);
		
		while (c.moveToNext()) {
			byte[] in=c.getBlob(c.getColumnIndex("Thumbnail"));  
			thumbnail = BitmapFactory.decodeByteArray(in,0,in.length);  
		}
		c.close();
		return thumbnail;
	}

	public List<Order> getNotUploadOrderInfoList() {
		ArrayList<Order> orderList = new ArrayList<Order>();
		opendb();
		String selectQuery = "select * from orders where OrderStatus > ? and OrderStatus <?";
		Cursor c = sqlitedatabase.rawQuery(selectQuery, new String[]{String.valueOf(Order.ORDER_STATUS_NOT_PAY), String.valueOf(Order.ORDER_STATUS_UPLOADED)});
		while (c.moveToNext()) {
			Order order = new Order();
			order.setOrderId( c.getString(c.getColumnIndex("OrderId")));
			order.setOrderStatus( c.getInt(c.getColumnIndex("OrderStatus")));
			order.setZipFilePath(c.getString(c.getColumnIndex("ZipFilePath")));
			order.setZipFileCrc(c.getString(c.getColumnIndex("ZipFileCrc")));
			order.setUploadedFileUrl(c.getString(c.getColumnIndex("FileUrl")));
			order.setTemplateName(c.getString(c.getColumnIndex("TemplateName")));
			order.setWorksn(c.getString(c.getColumnIndex("Worksn")));
			order.setOrderDeliveryCycle(c.getString(c.getColumnIndex("OrderDeliveryCycle")));
			orderList.add(order);
		}
		c.close();
		closedb();
		return orderList;
	}
	
	//查询本地用户已付款，未上传完成的订单信息
	public List<Order> getUserNotUploadOrderInfoList(List<String> orderId ) {
//		String[] order_id = new String[orderId.size()];
		String selectQuery = "select * from orders where OrderId in (";
		StringBuffer sb = new StringBuffer(selectQuery);
		for(int i=0;i<orderId.size();i++){
			sb.append("'"+orderId.get(i)+"'");
			if(i<(orderId.size()-1)){
				sb.append(",");
			}
		}
		sb.append(");");
		Log.i("msg_sql", sb.toString());
		ArrayList<Order> orderList = new ArrayList<Order>();
		opendb();
		Cursor c = sqlitedatabase.rawQuery(sb.toString(), null);
//		ArrayList<Order> orderList = new ArrayList<Order>();
//		opendb();
//		String selectQuery = "select * from orders where OrderId in ";
//		Cursor c = sqlitedatabase.query("orders", null, "OrderId in "+order_id, null, null, null, null);
//		Cursor c = sqlitedatabase.rawQuery(selectQuery, order_id);
		while (c.moveToNext()) {
			Order order = new Order();
			order.setOrderId( c.getString(c.getColumnIndex("OrderId")));
			order.setOrderStatus( c.getInt(c.getColumnIndex("OrderStatus")));
			order.setZipFilePath(c.getString(c.getColumnIndex("ZipFilePath")));
			order.setZipFileCrc(c.getString(c.getColumnIndex("ZipFileCrc")));
			order.setUploadedFileUrl(c.getString(c.getColumnIndex("FileUrl")));
			order.setTemplateName(c.getString(c.getColumnIndex("TemplateName")));
			order.setWorksn(c.getString(c.getColumnIndex("Worksn")));
			order.setOrderDeliveryCycle(c.getString(c.getColumnIndex("OrderDeliveryCycle")));
			orderList.add(order);
		}
		c.close();
		closedb();
		return orderList;
	}
	
}
